import { defineStore } from 'pinia';
import { ref } from 'vue';
import db from '@/data/db';

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref({
    username: '健身达人',
    age: null,
    height: null,
    gender: 'male'
  });

  // 从本地存储加载数据
  const loadUserInfo = () => {
    try {
      const savedUserInfo = localStorage.getItem('userInfo');
      if (savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo);
      } else {
        // 从数据库加载默认用户信息
        userInfo.value = { ...db.users[0] };
      }
    } catch (error) {
      console.error('Failed to load user info:', error);
    }
  };

  // 保存数据到本地存储
  const saveUserInfo = (info) => {
    try {
      userInfo.value = {
        ...userInfo.value,
        ...info
      };
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
    } catch (error) {
      console.error('Failed to save user info:', error);
    }
  };

  // 初始化
  loadUserInfo();

  // 动作
  const getUserInfo = () => {
    return userInfo.value;
  };

  const updateUserInfo = (newInfo) => {
    saveUserInfo(newInfo);
  };

  const clearData = () => {
    userInfo.value = {
      username: '健身达人',
      age: null,
      height: null,
      gender: 'male'
    };
    localStorage.removeItem('userInfo');
  };

  return {
    userInfo,
    getUserInfo,
    updateUserInfo,
    clearData
  };
});